<template>
  <div class="url-picture-upload">
    <a-input-group compact>
      <a-input v-model:value="fileUrl" style="width: calc(100% - 120px)" placeholder="请输入 URL"/>
      <a-button type="primary" style="width: 120px" :loading="loading" @click="handleUpLoad">提交</a-button>
    </a-input-group>
    <div class="image-wrapper">
      <img v-if="picture?.url" :src="picture?.url" alt="avatar" />
    </div>
  </div>
</template>


<script lang="ts" setup>
import { ref } from 'vue';
import { message } from 'ant-design-vue';
import { uploadPictureByUrlUsingPost} from '@/api/pictureController.ts'



const fileUrl = ref<string>();
const loading = ref<boolean>(false);
interface Props{
  picture?:API.PictureVO
  onSuccess?:(newPicture:API.PictureVO) => void
  spaceId?:number
}
const props=defineProps<Props>()

//上传文件
const handleUpLoad=async ()=>{
    loading.value=true;
    try {
      const params:API.PictureUploadRequest={fileUrl:fileUrl.value}
      params.spaceId=props.spaceId
      if(props.picture){
        params.id=props.picture.id;
      }
      const res= await uploadPictureByUrlUsingPost(params)
      if(res.data.code===0 && res.data.data){
        message.success("文件上传成功")
        //将上传成功的信息，上传给父组件
        props.onSuccess?.(res.data.data)
      }else {
        message.error("上传文件失败:"+res.data.message)
      }
    }catch(err){
       console.log(err)
       message.error("上传文件失败:"+err.message)
    }
    loading.value=false;
}

</script>


<style scoped>
.url-picture-upload {
  margin-bottom: 16px;
}

.url-picture-upload img {
  max-width: 100%;
  max-height: 480px;
}

.url-picture-upload .image-wrapper{
  text-align: center;
  margin-top: 16px;
}
</style>
